# import subprocess
# from nonebot import on_regex
# from nonebot.adapters.onebot.v11 import Message, GroupMessageEvent, Bot

# # 监听消息中是否包含"free"，不区分大小写
# free_command = on_regex(pattern=r'(?i)^free$', priority=1)

# @free_command.handle()
# async def handle_free(bot: Bot, event: GroupMessageEvent):
#     try:
#         # 执行free -m命令
#         result = subprocess.run(['free', '-m'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        
#         if result.stderr:
#             await free_command.finish(message=Message(f"执行free时出现错误: {result.stderr}"))
        
#         # 获取命令输出
#         free_output = result.stdout
#         await free_command.finish(message=Message(f"当前内存状态:\n{free_output}"))

#     except Exception as e:
#         print(f"发生错误: {e}")
#         # await free_command.finish(message=Message(f"发生错误: {e}"))


import psutil
from nonebot import on_regex
from nonebot.adapters.onebot.v11 import Message, GroupMessageEvent, Bot
from nonebot.exception import FinishedException  # 引入 FinishedException

# 监听消息中是否包含"free"，不区分大小写
free_command = on_regex(pattern=r'(?i)^free$', priority=1)

@free_command.handle()
async def handle_free(bot: Bot, event: GroupMessageEvent):
    try:
        # 获取内存使用情况
        memory = psutil.virtual_memory()
        total_mem_mb = memory.total / (1024 ** 2)  # 转换为MB
        used_mem_mb = memory.used / (1024 ** 2)    # 转换为MB
        mem_usage_percent = memory.percent

        # 构造消息
        message = (
            f"当前使用内存: {used_mem_mb:.2f} MB / 总内存: {total_mem_mb:.2f} MB，"
            f"使用率: {mem_usage_percent:.2f}%"
        )
        await free_command.finish(message=Message(message))

    except Exception as e:
        # 判断异常类型
        if not isinstance(e, FinishedException):
            print(f"发生错误: {e}")
            await free_command.finish(message=Message(f"发生错误: {e}"))
